import traceback

from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend

from utils.validator import CustomValidationError

UserModel = get_user_model()


class CustomBackend(ModelBackend):
    """
    Django原生认证方式
    """

    def authenticate(self, request, username=None, password=None, **kwargs):

        if username is None:
            username = kwargs.get(UserModel.USERNAME_FIELD)
        if username is None or password is None:
            return
        try:
            user = UserModel._default_manager.get_by_natural_key(username)
        except Exception:
            pass
            # print(traceback.format_exc())
        # except UserModel.DoesNotExist:
        #     # Run the default password hasher once to reduce the timing
        #     # difference between an existing and a nonexistent user (#20760).
        #     UserModel().set_password(password)
        else:
            if user.check_password(password):
                if self.user_can_authenticate(user):
                    return user
                else:
                    raise CustomValidationError("当前用户已被禁用，请联系客服或管理员!")


